package com.dingwen.treasure.kettle.init;

import cn.hutool.extra.spring.SpringUtil;
import com.dingwen.treasure.kettle.config.KettleConfig;
import com.dingwen.treasure.kettle.bo.DatabaseMetaBo;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
import org.pentaho.di.repository.kdr.KettleDatabaseRepositoryMeta;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 　KettleDatabaseRepository: kettle 数据资源库初始化
 * 　@author dingwen
 * 　@date 2022/8/20
 */
@Component
@Log4j2
@Order(-1)
@DependsOn("kettleConfig")
public class KettleDatabaseRepositoryInit implements InitializingBean {

    @Resource
    private KettleConfig kettleConfig;

    @Override
    @SneakyThrows
    public void afterPropertiesSet() {
        KettleEnvironment.init();
        DatabaseMetaBo databaseMetaBo = kettleConfig.getDatabaseMeta();
        DatabaseMeta databaseMeta = new DatabaseMeta(
                databaseMetaBo.getName(),
                databaseMetaBo.getType(),
                databaseMetaBo.getAccess(),
                databaseMetaBo.getHost(),
                databaseMetaBo.getDb(),
                databaseMetaBo.getPort(),
                databaseMetaBo.getUser(),
                databaseMetaBo.getPass()
        );
        KettleDatabaseRepositoryMeta kettleDatabaseRepositoryMeta = new KettleDatabaseRepositoryMeta();
        kettleDatabaseRepositoryMeta.setConnection(databaseMeta);

        KettleDatabaseRepository kettleDatabaseRepository = new KettleDatabaseRepository();

        kettleDatabaseRepository.init(kettleDatabaseRepositoryMeta);

        kettleDatabaseRepository.connect(
                databaseMetaBo.getRepositoryUsername(),
                databaseMetaBo.getRepositoryPassword()
        );

        SpringUtil.registerBean("kettleDatabaseRepository",kettleDatabaseRepository);
    }
}
